package cn.bellychang.tomcat;

import org.apache.catalina.core.StandardContext;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Configuration;

/**
 * @author ChangLiang
 * @date 2020/2/21
 */
@Configuration
public class TomcatConfiguration implements EmbeddedServletContainerCustomizer {

    @Override
    public void customize(ConfigurableEmbeddedServletContainer configurableEmbeddedServletContainer) {
        System.err.println(configurableEmbeddedServletContainer.getClass());
        if (configurableEmbeddedServletContainer instanceof TomcatEmbeddedServletContainerFactory) {
            TomcatEmbeddedServletContainerFactory factory =
                    (TomcatEmbeddedServletContainerFactory) configurableEmbeddedServletContainer;
            /// in this way 8080 and 9090 will be all started
/*            Connector connector = new Connector();
            connector.setPort(9090);
            connector.setURIEncoding("UTF-8");
            connector.setProtocol("HTTP/1.1");
            factory.addAdditionalTomcatConnectors(connector);*/

            // switch off DefaultServlet
            configurableEmbeddedServletContainer.setRegisterDefaultServlet(false);

            factory.addContextCustomizers((context)->{
                if (context instanceof StandardContext) {
                    StandardContext standardContext = (StandardContext) context;
                    /*standardContext.setDefaultWebXml("");
                    standardContext.setName("");
                    standardContext.setPath("");
                    standardContext.setDocBase("");*/
                }
            });

            /**
             * in this way, only 9090 start
             */
            factory.addConnectorCustomizers((connector -> {
                connector.setPort(9090);
            }));
        }
    }
}
